import { defineStore } from "pinia";
import { LoginData } from "@/api/user/types";
import { loginApi } from "@/api/user";
import { useStorage } from "@vueuse/core";
import { store } from "@/store";
import { ref } from "vue";

export const useUserStore = defineStore("user", () => {
  // token
  const accessToken = useStorage("token", "");

  // userInfo
  const userInfo = useStorage("userInfo", {});

  /**
   * 登录
   */
  function login(data: LoginData) {
    return new Promise<void>((resolve, reject) => {
      accessToken.value = "asdsafsafdsfdsgds";
      userInfo.value = {
        username: "admin",
        nickname: "管理員",
        password: "123456",
        icon: "",
      };
      // loginApi(data)
      //   .then((response) => {
      //     const { token, userInfo: user } = response;
      //     // accessToken.value = token;
      //     // userInfo.value = user;
      //     accessToken.value = "asdsafsafdsfdsgds";
      //     userInfo.value = {
      //       username: "admin",
      //       nickname: "管理員",
      //       password: "123456",
      //       icon: "",
      //     };
      //     resolve();
      //   })
      //   .catch(() => {
      //     reject();
      //   });
    });
  }

  function resetStore() {
    accessToken.value = "";
    userInfo.value = {};
  }
  /**
   * 退出登录
   */
  function logout() {
    return new Promise((resolve, reject) => {
      resetStore();
      resolve();
    });
  }
  return { accessToken, userInfo, login, logout };
});

// 非setup
export function useUserStoreHook() {
  return useUserStore(store);
}
